package pinkblob.event;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import pinkblob.entity.ProjectInformation;

public class ProjectInformationHandler extends AProjectInformationHandler {

	public ProjectInformationHandler() {
		super();
	}

	public void transactionStart() {
		em.getTransaction().begin();
	}

	public void transactionRollback() {
		em.getTransaction().rollback();
	}

	public void transactionCommit() {
		em.getTransaction().commit();
	}

	public Map<String, Object> getSingleGarbageProjectInformation() {
		em.getTransaction().begin();
		Query q = em.createQuery("select pi from ProjectInformation pi");
		try {
			@SuppressWarnings("unchecked")
			List projectinformations = q.getResultList();
			for (Object pi_o : projectinformations) {
				// TODO: Bedingungen fuer Abbruch einfuegen und die globale
				// setzen
				// (die kotzt mich echt an, muesste man mal umbauen)
				ProjectInformation projectinformation = (ProjectInformation) pi_o;
				if (projectinformation.getIterations() > 10 && true) { // statt
																		// dem
																		// true
																		// neue
																		// bedingung
																		// einfuegen
																		// usw
					projectinformation.setStatus(999);
					pi = projectinformation;
				}
			}
		} catch (NoResultException ex) {
			pi = new ProjectInformation();
			pi.setPid(-1);
			pi.setComment("This is a dummy, which will be returned, "
					+ "if no projects are in the database");
			em.persist(pi);
		}
		em.getTransaction().commit();
		return getProjectInformationMap();

	}

	public void setNewDeadline(Integer pid, Date date) {
		em.getTransaction().begin();
		ProjectInformation pr_i = null;
		Query q = em
				.createQuery("select pi from ProjectInformation pi where pi.Pid = :pid");
		q.setParameter("pid", pid);
		try {
			log.debug(q.toString());
			pr_i = (ProjectInformation) q.getSingleResult();
			log.debug("Setting dl to: "+date);
			pr_i.setDeadline(date);
		} catch (NoResultException ex) {
			throw ex;
		}
		em.getTransaction().commit();
	}

	public void setStatus(Integer pid, Integer status) {
		em.getTransaction().begin();
		ProjectInformation pr_i = null;
		Query q = em
				.createQuery("select pi from ProjectInformation pi where pi.Pid = :pid");
		q.setParameter("pid", pid);
		try {
			log.debug(q.toString());
			pr_i = (ProjectInformation) q.getSingleResult();
			log.debug("Setting status to: "+status);
			pr_i.setStatus(status);
		} catch (NoResultException ex) {
			throw ex;
		}
		em.getTransaction().commit();	
	}
	
}
